#include "Chunk.h"
#include "Types.h"
#include "base.h"
#include "Constant.h"
#include "ChunkManager.h"
#include "ScrGame.h"

Chunk::Chunk(ChunkManager *pChunkManager, int x, int z)
{
	m_pChunkManager = pChunkManager;
	m_nXPos = x;
	m_nZPos = z;
	m_bAllowUnload = true;
}
Chunk::~Chunk(void)
{
}
void Chunk::Generate()
{
	m_blockIndex = Shared_BlockBuffer(new uint[blockDataLength]);
	m_sliceInfo = Shared_SliceInfo(new ChunkSliceInfo[chunkHSliceCount]);

	memset(m_blockIndex.get(), 0, blockDataLength * sizeof(uint));

	//Generate flatlands starting at y-level 63
	for(uint z = 0; z < yBlocks; z++)
	{
		for(uint x = 0; x < xBlocks; x++)
		{
			uint *currentBlock = &m_blockIndex[CHUNK_INDEX(x,z, 63)];
			*currentBlock = ScrGame::blockGrass;
			//Dirt Layer
			for(int yBelow = 62; yBelow > 31; yBelow--)
			{
				m_blockIndex[CHUNK_INDEX(x,z,yBelow)] = ScrGame::blockDirt;
			}
			//Stone Layer
			for(int yBelow = 31; yBelow > 7; yBelow--)
			{
				m_blockIndex[CHUNK_INDEX(x,z,yBelow)] = ScrGame::blockStone;
			}
			//Bedrock Layer
			for(int yBelow = 7; yBelow > 0; yBelow--)
			{
				m_blockIndex[CHUNK_INDEX(x,z,yBelow)] = ScrGame::blockBedrock;
			}
		}
	}

	//Update slices
	for(uint si = 0; si < chunkHSliceCount; si++)
	{
		uint *pSlicePtr = &m_blockIndex.get()[Chunk::chunkHSliceLength * si];
		m_sliceInfo[si].Update(pSlicePtr);
	}
}
void Chunk::Draw(BlockRenderer *blockRenderer)
{
	uint blockID = 0;
	for(int i = 0; i < chunkHSliceCount; i++)
	{
		if(m_sliceInfo[i].IsVisible())
		{
			for(int x = 0; x < xBlocks; x++)
			{
				for(int z = 0; z < zBlocks; z++)
				{
					for(int y = 0; y < chunkHSliceHeight; y++)
					{
						blockID = m_blockIndex[CHUNKSLICE_INDEX(x,z,y,i)];
						if(blockID != 0)
						{
							blockRenderer->DrawBlockAlt(vector3( (int)(x+(m_nXPos*xBlocks)),(int)y,(int)(z+(m_nZPos*zBlocks)) ), blockID);
						}
					}
				}
			}
		}
	}
	return;
}
